package com.dqhl.community.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.ApplianceCleanAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.FamilyProjectBean;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.view.LuocangDialog;
import com.dqhl.community.view.MyGridView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

/**
 * 首页
 * 家电清洗
 * Created by liming on 2016/8/31.
 */
public class ApplianceCleanActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ImageView mIvadd, mIvJian;
    private TextView mTvNumber, mTvMoney;
    private TextView mTvAllMoney;
    //    private  int money=0;
    private int num = 0;
    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private ImageView ivWasher, ivMicrowave, ivFreezer, ivSmoke, ivWater, ivAir;
    private RelativeLayout layout_aircondit;
    private RelativeLayout layout_total;
    private Button btnAppoint;
    private MyGridView gvAppliance;
    private EditText mEtName;//姓名
    private EditText mEtPhoto;//电话
    private EditText mEtAddress;//地址
    private LinearLayout cleanProject;
    private TextView mTvProjectName;
    private LuocangDialog dialog;
    private List<FamilyProjectBean> cleanProjectBeen;
    //    private SharedPreferences sp;
    private String money;//单价
    private String project_id;//清洗项目id
    //定位所在小区
    private TextView tv_cleanCommunity;
    private TextView tv_cleanNoData;
    private static int REQUEST_CODE = 100;
    private String location = "";
    private String location_id = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appliance_clean);
        initView();
        //进入界面需先定位小区
        final LuocangDialog dialog = new LuocangDialog(ApplianceCleanActivity.this, "", "请先定位所在小区", "确认");
        dialog.setButtonClickListener(new LuocangDialog.ButtonClickListener() {
            @Override
            public void doConfirm() {
                dialog.dismiss();
                overlay(LocationClearActivity.class, REQUEST_CODE);
            }
        });
        dialog.show();

    }

    private void initView() {
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        btnAppoint = (Button) findViewById(R.id.btn_appoint);
        layout_aircondit = (RelativeLayout) findViewById(R.id.layout_aircondit);
        layout_total = (RelativeLayout) findViewById(R.id.layout_total);
        layout_aircondit.setVisibility(View.GONE);
        layout_total.setVisibility(View.GONE);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        gvAppliance = (MyGridView) findViewById(R.id.gv_appliance_project);
        mEtName = (EditText) findViewById(R.id.et_clearName);
        mEtPhoto = (EditText) findViewById(R.id.et_clearPhoto);
        mEtAddress = (EditText) findViewById(R.id.et_clearAddress);
        tvTopTitle.setText("家电清洗");

        mTvNumber = (TextView) findViewById(R.id.tv_counts);
        mIvJian = (ImageView) findViewById(R.id.iv_minus);
        mIvadd = (ImageView) findViewById(R.id.iv_plus);
        mTvAllMoney = (TextView) findViewById(R.id.tv_sum);
        mTvProjectName = (TextView) findViewById(R.id.tv_projectname);
        mTvMoney = (TextView) findViewById(R.id.tv_price);
        tv_cleanCommunity = (TextView) findViewById(R.id.tv_cleanCommunity);
        tv_cleanNoData = (TextView) findViewById(R.id.tv_clean_nodata);
        //实例化对象
        ivTopBack.setOnClickListener(this);
        btnAppoint.setOnClickListener(this);
        mIvJian.setOnClickListener(this);
        mIvadd.setOnClickListener(this);
        gvAppliance.setOnItemClickListener(this);
        tv_cleanCommunity.setOnClickListener(this);
        if (num == 0) {
            mIvJian.setVisibility(View.GONE);
        }

//        String communityName = spUserInfo.getString(Constant.COMMUNITY_ID, "定位所有小区");
//        tv_cleanCommunity.setText(communityName);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_minus:
                if (num > 0) {
                    mTvNumber.setText((--num) + "");
                    mTvAllMoney.setText("¥" + Integer.valueOf(money) * num);
                    if (num == 0) {
                        mIvJian.setVisibility(View.GONE);
                    }
                }
                break;
            //加
            case R.id.iv_plus:
                mTvNumber.setText(++num + "");
                mTvAllMoney.setText("¥" + Integer.valueOf(money) * num);
                if (num > 0) {
                    mIvJian.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.btn_appoint: //预约成功toast
                String name = mEtName.getText().toString();
                String phone = mEtPhoto.getText().toString();
                String address = mEtAddress.getText().toString();
                String userid = spUserInfo.getString(Constant.USERID, "");
//                String userid = sp.getString(Constant.USERID, "");
                Dlog.e("GGlocation" + location);
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(address) && !TextUtils.isEmpty(userid) && !TextUtils.isEmpty(project_id) && !TextUtils.isEmpty(location)) {
                    commitDate(name, phone, address, project_id, userid, location);
                } else {
                    toast("请完善信息");
                }
                break;
            case R.id.tv_cleanCommunity:
                overlay(LocationClearActivity.class, REQUEST_CODE);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        layout_aircondit.setVisibility(View.VISIBLE);
        layout_total.setVisibility(View.VISIBLE);
        FamilyProjectBean item = (FamilyProjectBean) adapterView.getItemAtPosition(i);
        mTvProjectName.setText(item.getType());
        mTvMoney.setText(item.getPrice());
        money = item.getMoney();
        project_id = item.getId();
        mTvNumber.setText(num + "");
        mTvAllMoney.setText("¥  0");
    }

    /**
     * 家电清洗项目
     */
    private void getDate() {
        showCustomLoadBar(R.string.loading);
        num = 0;
        mTvNumber.setText("0");
        mTvAllMoney.setText("¥  0");
        RequestParams params = new RequestParams(Config.Api.clean_project);
        params.addBodyParameter("community_id", location_id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG清洗返回项目" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String data = JsonUtils.getInfo(result, "data");
                    cleanProjectBeen = JSON.parseArray(data, FamilyProjectBean.class);
                    Dlog.e("GG清洗返回项目cleanProjectBeen" + cleanProjectBeen);
                    if (cleanProjectBeen.size() > 0) {
                        final ApplianceCleanAdapter cleanAdapter = new ApplianceCleanAdapter(ApplianceCleanActivity.this, cleanProjectBeen);
                        tv_cleanNoData.setVisibility(View.GONE);
                        gvAppliance.setVisibility(View.VISIBLE);
                        gvAppliance.setAdapter(cleanAdapter);
                        gvAppliance.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                FamilyProjectBean item = (FamilyProjectBean) adapterView.getItemAtPosition(position);
                                layout_aircondit.setVisibility(View.VISIBLE);
                                layout_total.setVisibility(View.VISIBLE);
                                mTvProjectName.setText(item.getType());
                                mTvMoney.setText(item.getPrice());
                                money = item.getMoney();
                                project_id = item.getId();
                                Dlog.e("GG清洗返回的ID " + item.getId());
                                mTvNumber.setText("0");
                                mTvAllMoney.setText("¥  0");
                                cleanAdapter.clearSelection(position);
                                cleanAdapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        layout_aircondit.setVisibility(View.GONE);
                        layout_total.setVisibility(View.GONE);
                        gvAppliance.setVisibility(View.GONE);
                        tv_cleanNoData.setVisibility(View.VISIBLE);
                        tv_cleanNoData.setText(R.string.error_no_info);
                    }
                } else {
                    tv_cleanNoData.setVisibility(View.VISIBLE);
                    tv_cleanNoData.setText(R.string.error_server_connection);
                    Log.d("ApplianceCleanActivity", "数据请求失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                tv_cleanNoData.setVisibility(View.VISIBLE);
                tv_cleanNoData.setText(R.string.error_net_connection);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void commitDate(String name, String phone, String address, String project_id, String userid, String location) {
        showCustomLoadBar(R.string.loading);
        RequestParams params = new RequestParams(Config.Api.family_clean);
        params.addBodyParameter("name", name);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("address", address);
        params.addBodyParameter("project_id", project_id);
        params.addBodyParameter("userid", userid);
        params.addBodyParameter("location", location);
        Dlog.e("GG");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GGApplianceCleanActivity" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String errMsg = JsonUtils.getInfo(result, "errMsg");
                    if ("预约成功".equals(errMsg)) {
                        final LuocangDialog dialog = new LuocangDialog(ApplianceCleanActivity.this, errMsg, "我们会尽快联系您", "确认");
                        dialog.setButtonClickListener(new LuocangDialog.ButtonClickListener() {
                            @Override
                            public void doConfirm() {
                                dialog.dismiss();
                                forward(ApplianceCleanRecordActivity.class);
                            }
                        });
                        dialog.show();
                    }
                } else {
                    toast("预约失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                toast(R.string.error_net_connection);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                Dlog.e(bundle.getString("community_id") + "GG返回的数据" + bundle.getString("community_name"));
                location = bundle.getString("community_name");
                location_id = bundle.getString("community_id");
                tv_cleanCommunity.setText(bundle.getString("community_name"));
                getDate();
            }
        }

    }
}

